var express = require('express');
var router = express.Router();
const low = require('lowdb');
const FileSync = require('lowdb/adapters/FileSync');

const adapter = new FileSync(__dirname + '/../data/db.json');
const db = low(adapter);


const shortid = require('shortid');
//账本列表
router.get('/accounts',(req,res,next) => {
  let accounts = db.get('accounts').value();
  res.render('index',{accounts:accounts});
});

//添加账本
router.get('/accounts/add',(req,res,next) => {
  res.render('create');
})

router.post('/accounts',(req, res) => {
  let id = shortid.generate();
  db.get('accounts').unshift({id:id,...req.body}).write();
  res.render('success',{msg:'添加成功~~~',url:'/accounts'})
})


router.get('/accounts/:id' ,(req, res) => {
  let id = req.params.id;
  db.get('accounts').remove({id:id}).write();
  res.render('success',{msg:'删除成功~~~',url:'/accounts'})
})

module.exports = router;
